<template>
  <div class="medical-container">
    <el-card class="credit-check-card">
      <template #header>
        <div class="card-header">
          <span>信用就医资格</span>
          <el-button type="primary" @click="checkCredit">检查资格</el-button>
        </div>
      </template>
      <div v-if="creditInfo" class="credit-info">
        <el-alert
          :type="creditInfo.canUse ? 'success' : 'warning'"
          :title="creditInfo.canUse ? '您可以使用信用就医服务' : '您的信用分不足，无法使用信用就医服务'"
          :description="`所需信用分：${creditInfo.requiredScore}`"
          show-icon
        />
      </div>
    </el-card>

    <el-card class="medical-form-card">
      <template #header>
        <div class="card-header">
          <span>开始就医</span>
        </div>
      </template>
      <el-form :model="form" label-width="100px">
        <el-form-item label="选择医院">
          <el-select v-model="form.hospitalName" placeholder="请选择医院" @change="handleHospitalChange">
            <el-option
              v-for="hospital in hospitals"
              :key="hospital"
              :label="hospital"
              :value="hospital"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="选择科室">
          <el-select v-model="form.department" placeholder="请选择科室" @change="handleDepartmentChange">
            <el-option
              v-for="dept in departments"
              :key="dept"
              :label="dept"
              :value="dept"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="选择医生">
          <el-select v-model="form.doctorName" placeholder="请选择医生">
            <el-option
              v-for="doctor in doctors"
              :key="doctor"
              :label="doctor"
              :value="doctor"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="startVisit" :disabled="!canStartVisit">
            开始就医
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="medical-records-card">
      <template #header>
        <div class="card-header">
          <span>就医记录</span>
          <el-button type="primary" @click="loadRecords">刷新</el-button>
        </div>
      </template>
      <el-table :data="records" style="width: 100%">
        <el-table-column prop="hospitalName" label="医院" />
        <el-table-column prop="department" label="科室" />
        <el-table-column prop="doctorName" label="医生" />
        <el-table-column prop="visitTime" label="开始时间">
          <template #default="scope">
            {{ formatDateTime(scope.row.visitTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间">
          <template #default="scope">
            {{ scope.row.endTime ? formatDateTime(scope.row.endTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 'IN_PROGRESS'"
              type="primary"
              size="small"
              @click="endVisit(scope.row.id)"
            >
              结束就医
            </el-button>
            <el-button
              v-if="scope.row.status === 'PENDING_PAYMENT'"
              type="success"
              size="small"
              @click="handlePayment(scope.row)"
            >
              支付
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加支付对话框组件 -->
    <medical-payment-dialog
      v-model="paymentDialogVisible"
      :record="selectedRecord"
      @payment-success="handlePaymentSuccess"
    />
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { formatDateTime } from '@/utils/format'
import { medicalApi } from '@/api/medical'
import MedicalPaymentDialog from '@/components/payment/MedicalPaymentDialog.vue'

export default {
  name: 'Medical',
  components: {
    MedicalPaymentDialog
  },
  setup() {
    const store = useStore()
    const userId = computed(() => store.state.user.id)

    const creditInfo = ref(null)
    const hospitals = ref([])
    const departments = ref([])
    const doctors = ref([])
    const records = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    const form = ref({
      hospitalName: '',
      department: '',
      doctorName: ''
    })

    const canStartVisit = computed(() => {
      return form.value.hospitalName && 
             form.value.department && 
             form.value.doctorName
    })

    const paymentDialogVisible = ref(false)
    const selectedRecord = ref(null)

    const checkCredit = async () => {
      try {
        const response = await medicalApi.checkCredit(userId.value)
        creditInfo.value = response.data
      } catch (error) {
        ElMessage.error('检查信用资格失败')
      }
    }

    const loadHospitals = async () => {
      try {
        const response = await medicalApi.getHospitals()
        hospitals.value = response.data
      } catch (error) {
        ElMessage.error('获取医院列表失败')
      }
    }

    const handleHospitalChange = async () => {
      form.value.department = ''
      form.value.doctorName = ''
      departments.value = []
      doctors.value = []
      
      if (form.value.hospitalName) {
        try {
          const response = await medicalApi.getDepartments(form.value.hospitalName)
          departments.value = response.data
        } catch (error) {
          ElMessage.error('获取科室列表失败')
        }
      }
    }

    const handleDepartmentChange = async () => {
      form.value.doctorName = ''
      doctors.value = []
      
      if (form.value.hospitalName && form.value.department) {
        try {
          const response = await medicalApi.getDoctors(
            form.value.hospitalName,
            form.value.department
          )
          doctors.value = response.data
        } catch (error) {
          ElMessage.error('获取医生列表失败')
        }
      }
    }

    const startVisit = async () => {
      try {
        await medicalApi.startVisit({
          userId: userId.value,
          ...form.value
        })
        ElMessage.success('开始就医成功')
        loadRecords()
        form.value = {
          hospitalName: '',
          department: '',
          doctorName: ''
        }
      } catch (error) {
        ElMessage.error(error.response?.data || '开始就医失败')
      }
    }

    const endVisit = async (recordId) => {
      try {
        await medicalApi.endVisit(recordId)
        ElMessage.success('结束就医成功')
        loadRecords()
      } catch (error) {
        ElMessage.error('结束就医失败')
      }
    }

    const loadRecords = async () => {
      try {
        const response = await medicalApi.getRecords(
          userId.value,
          currentPage.value - 1,
          pageSize.value
        )
        records.value = response.data.content
        total.value = response.data.totalElements
      } catch (error) {
        ElMessage.error('获取就医记录失败')
      }
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      loadRecords()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadRecords()
    }

    const getStatusType = (status) => {
      const types = {
        'IN_PROGRESS': 'warning',
        'PENDING_PAYMENT': 'danger',
        'COMPLETED': 'success'
      }
      return types[status] || 'info'
    }

    const getStatusText = (status) => {
      const texts = {
        'IN_PROGRESS': '就医中',
        'PENDING_PAYMENT': '待支付',
        'COMPLETED': '已完成'
      }
      return texts[status] || status
    }

    const handlePayment = (record) => {
      selectedRecord.value = record
      paymentDialogVisible.value = true
    }

    const handlePaymentSuccess = () => {
      loadRecords()
    }

    onMounted(() => {
      checkCredit()
      loadHospitals()
      loadRecords()
    })

    return {
      creditInfo,
      hospitals,
      departments,
      doctors,
      form,
      records,
      currentPage,
      pageSize,
      total,
      canStartVisit,
      checkCredit,
      handleHospitalChange,
      handleDepartmentChange,
      startVisit,
      endVisit,
      loadRecords,
      handleSizeChange,
      handleCurrentChange,
      getStatusType,
      getStatusText,
      handlePayment,
      formatDateTime,
      paymentDialogVisible,
      selectedRecord,
      handlePaymentSuccess
    }
  }
}
</script>

<style scoped>
.medical-container {
  padding: 20px;
}

.credit-check-card,
.medical-form-card,
.medical-records-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.credit-info {
  margin-top: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 